
package com.borqs.music.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class HttpRequestUtils {
    private static final String JPEG = "image/jpeg";
    private static final String GIF = "image/gif";
    private static final String PNG = "image/png";
    private static final String OCTET = "application/octet-stream";

    /**
     * @return content-type
     */
    public static String getContentType(File file) {
        if (file == null) {
            throw new IllegalArgumentException("File = null");
        }

        String contentType;
        String fileName = file.getName();
        int index = fileName.lastIndexOf(".");
        if (-1 == index) {
            // no extension
            contentType = OCTET;
        } else {
            String extensions = fileName.substring(index + 1).toLowerCase();
            if (extensions.length() == 3) {
                if ("gif".equals(extensions)) {
                    contentType = GIF;
                } else if ("png".equals(extensions)) {
                    contentType = PNG;
                } else if ("jpg".equals(extensions)) {
                    contentType = JPEG;
                } else {
                    contentType = OCTET;
                }
            } else if (extensions.length() == 4) {
                if ("jpeg".equals(extensions)) {
                    contentType = JPEG;
                } else {
                    contentType = OCTET;
                }
            } else {
                contentType = OCTET;
            }
        }

        return contentType;
    }
    
    public static String encodeParameters(Map<String, String> httpParams) {
        if (null == httpParams) {
            return "";
        }
        
        StringBuffer buf = new StringBuffer();
        boolean appendAnd = false;
        for (Map.Entry<String, String> param : httpParams.entrySet()) {
            if (appendAnd) {
                buf.append("&");
            } else {
                appendAnd = true;
            }

            try {
                buf.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                buf.append("=");
                buf.append(URLEncoder.encode(param.getValue(), "UTF-8"));
            } catch (UnsupportedEncodingException uEx) {
                uEx.printStackTrace();
            }
        }

        return buf.toString();
    }
}
